<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;
use fast\Random;
// 废弃不用
class StudioPermissiomService
{
    // 列表
    public static function index($data)
    {
        $auth = Auth::instance();
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        //分页查询
        $studio = \app\admin\model\User::where(['studio_id'=>['<>', '']])->field('country, region, studio_id, username as account, plaintext as password')->order('id', 'desc')
            ->paginate($limit);
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$studio];
    }

    // 添加
    public static function add($data)
    {
        $auth = Auth::instance();
        // 验证规则 region_code，region_name，country_code 不为空且不重复
        $validate = new Validate([
            'studio_id' => 'require|unique:user,studio_id',
            'country' => 'require',
            'region' => 'require',
            'phone' => 'require|unique:user,phone',
            'email' => 'require|unique:user,email',
            'account' => 'require|unique:user,account',
            'password' => 'require',
        ], [
            'studio_id.require' => 'StudioID is not empty',
            'studio_id.unique' => 'StudioID is already exists',
            'country.require' => 'Country is not empty',
            'region.require' => 'Region is not empty',
            'phone.require' => 'Phone is not empty',
            'phone.unique' => 'Phone is already exists',
            'email.require' => 'Email is not empty',
            'email.unique' => 'Email is already exists',
            'account.require' => 'account is not empty',
            'account.unique' => 'account is already exists',
            'password.require' => 'Contact name is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        try {

            $result = $auth->register($data['account'], $data['password'], $data['email'], $data['phone'], ['group_id'=>2, 'studio_id'=>$data['studio_id'], 'country'=>$data['country'], 'region'=>$data['region'], 'plaintext'=>$data['password']]);
//            $result = \app\admin\model\User::create($data);
            // 后期补权限问题

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 编辑
    public static function edit($data)
    {
        $auth = Auth::instance();
        // 验证规则 region_code，region_name，country_code 不为空且不重复
        $validate = new Validate([
            'studio_id' => 'require',
            'country' => 'require',
            'region' => 'require',
            'phone' => 'require|unique:user,mobile',
            'email' => 'require|unique:user,email',
            'account' => 'require|unique:user,username',
            'password' => 'require',
        ], [
            'studio_id.require' => 'StudioID is not empty',
            'country.require' => 'Country is not empty',
            'region.require' => 'Region is not empty',
            'phone.require' => 'Phone is not empty',
            'phone.unique' => 'Phone is already exists',
            'email.require' => 'Email is not empty',
            'email.unique' => 'Email is already exists',
            'account.require' => 'account is not empty',
            'account.unique' => 'account is already exists',
            'password.require' => 'Contact name is not empty',
        ]);

        $user_id = \app\admin\model\User::where(['studio_id'=>$data['studio_id']])->value('id');

        if($user_id != $data['id']) return ['code'=>400, 'msg'=>'StudioID is already exists', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
//        return $data;
        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        try {

            $data['plaintext'] = $data['password'];
            $data['username'] = $data['account'];
            $data['mobile'] = $data['phone'];
            unset($data['account']);
            unset($data['phone']);
            $result = \app\admin\model\User::update($data);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }
    // 删除
    public static function del($data)
    {
        $auth = Auth::instance();
        // 验证$data['id']是否为空且为数字
        if (empty($data['id']) || !is_numeric($data['id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }
        // 查询学习馆数据
        $info = \app\admin\model\User::find($data['id']);
        if (!$info) {
            return ['code'=>400, 'msg'=>'Info does not exist', 'state'=>'NOT_FOUND', 'data'=>null];
        }

        // 启用事务删除数据
        try {
            $result = \app\admin\model\User::destroy($data['id']);

            if($result){
                // TODO删除关联数据

                // TODO转移老师、学员数据

                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }



    
}
